/*
 * Created on Oct 4, 2003
 *
 * Mihai Postelnicu
 *
 */
package ro.gateway.aida.struts.action;

import java.net.URLEncoder;

import javax.mail.internet.InternetAddress;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.tiles.actions.TilesAction;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.usr.User;
import ro.gateway.aida.usr.UserUtils;
import ro.gateway.aida.usr.messaging.LPDRelay;
import ro.gateway.aida.utils.BugTracker;
import ro.gateway.aida.utils.Utils;


/**
 * @author Mihai Postelnicu
 * MailAction
 *
 * */
public class SendByMailAction extends TilesAction {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) {
			ServletContext sc = getServlet().getServletContext();
        try {
            
            String ctx = request.getContextPath();
            String friendmail = request.getParameter("friendmail");
            String comment=request.getParameter("comment");
            String prjid = request.getParameter("prjid");
            String mode= request.getParameter("mode");
            User user = UserUtils.getLogged(request, response);
			PersistenceToken token = PersistenceManager.tokenLookup( sc );
			Utils.setBreadCrumbs(request,"bc.prjmail");
            if (user == null) {
                return mapping.findForward("empty");
            }


			if ("form".equals(mode) || friendmail==null || friendmail.trim().equals("")) {
				request.setAttribute("prjid",prjid);
				return mapping.findForward("sendform");
			}
            if ((friendmail == null) || (prjid == null)) {
                return mapping.findForward("error");
            }

            try {
                InternetAddress.parse(friendmail, true);
                Long.parseLong(prjid);
            } catch (Exception e) {
                return mapping.findForward("error");
            }
            
    		if(comment==null) comment=new String();
    		String adr=request.getRequestURL().toString().replaceFirst("sendbymail.do",
			"activity/mailview.jsp?id="+prjid+"&comment="+URLEncoder.encode(comment,"UTF-8"));
            String g = LPDRelay.getHTTP(adr);
            LPDRelay lpdr=LPDRelay.getManager(token);
            
            lpdr.sendMail(
                user.getFullName()+" sent you this LPD resource", g, friendmail);

			request.setAttribute("id",prjid);
            return mapping.findForward("mailsent");
        } catch (Exception e) {        	
        	BugTracker.publishBug(e, request);
            return mapping.findForward("fail");
        }
    }
}
